package com.cardone.persistent.support;

import com.cardone.context.ContextHolder;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 冗余更新
 * Created by Administrator on 2014/11/1.
 */
public class RedundancyUpdateAction implements UpdateAction {
    @Setter
    @Getter
    protected String[] names;

    @Setter
    protected String findSqlId = "/platform/findRedundancyByCode";

    @Setter
    protected String updateSqlId = "/platform/updateRedundancyByCode";

    @Setter
    protected List<String> fixSqlIds;
    //= Lists.newArrayList("/platform/updateDataStateId", "/platform/updateDataStateIdByEndDate");

    @Setter
    protected List<String> clearCacheNames;

    @Setter
    protected Map<String, Object> model;

    @Setter
    @Getter
    protected List<RedundancyUpdateAction> children;


    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void run() {
        JdbcTemplateSupport jdbcTemplateSupport = ContextHolder.getBean(JdbcTemplateSupport.class);

        if (StringUtils.isNotBlank(this.findSqlId)) {
            List<Map<String, Object>> updateMapList = jdbcTemplateSupport.findList(this.findSqlId, this.model);

            if (CollectionUtils.isNotEmpty(updateMapList) && StringUtils.isNotBlank(this.updateSqlId)) {
                jdbcTemplateSupport.batchUpdate(this.updateSqlId, this.model, updateMapList);

                if (CollectionUtils.isNotEmpty(this.children)) {
                    for (RedundancyUpdateAction redundancyUpdateAction : this.children) {
                        redundancyUpdateAction.run();
                    }
                }
            }
        }

        if (CollectionUtils.isNotEmpty(fixSqlIds)) {
            jdbcTemplateSupport.batchUpdateTry(fixSqlIds, model);
        }
    }
}
